package com.linyaonan.leetcode.medium._162;

/**
 * @author: Lin
 * @date: 2024/2/21
 */
public class FindPeakElement {

    public int findPeakElement(int[] nums) {
        // 1. 特殊情况
        if (nums.length == 1) {
            return 0;
        }
        // 2. 边界情况
        if (nums[0] > nums[1]) {
            return 0;
        }
        if (nums[nums.length - 1] > nums[nums.length - 2]) {
            return nums.length - 1;
        }

        // 3. 其他情况统一按照二分法查找
        int l = 0;
        int r = nums.length - 1;

        while (l <= r) {
            int m = (l + r) >>> 1;
            // 4. 边界再考虑
            if (m == 0) {
                if (nums[m + 1] > nums[m]) {
                    l = m + 1;
                } else {
                    return 0;
                }
                continue;
            }
            if (m == nums.length - 1) {
                if (nums[m - 1] > nums[m]) {
                    r = m - 1;
                } else {
                    return nums.length - 1;
                }
                continue;
            }
            // 5. 二分查找
            int midNum = nums[m];
            int leftNum = nums[m - 1];
            int rightNum = nums[m + 1];

            if (midNum > leftNum && midNum > rightNum) {
                return m;
            } else if (midNum > leftNum && midNum < rightNum) {
                // 处于一个上升趋势
                l = m + 1;
            } else if (midNum < leftNum && midNum > rightNum) {
                // 处于一个下降趋势
                r = m - 1;
            } else {
                // 中间值比两边都小，直接向右找
                l = m + 1;
            }
        }

        return 0;

    }

}
